#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Denis Mingulov
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


import os
import wsgiref.handlers

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

from engine import modules
from engine import persons

class MainHandler(webapp.RequestHandler):
    def updatePers(self, pers, name):
        text = self.request.get(name)
        if text is None:
            return False
        if len(text) <= 0:
            return False
        if not hasattr(pers, name):
            return False
        try:
            value = int(text)
        except ValueError:
            value = 0
        if getattr(pers, name) == value:
            return False
        setattr(pers, name, value)
        return True

    def get_page_data(self):
        pers = persons.getCurrentPerson()
#        print pers.persConsitution

        hashString = "modulePers_%s" % (pers.user.user_id())
        data = memcache.get( hashString )
        if data is not None:
            return data
        else:
            template_values = {
                'pers': pers,
                }
     
            path = os.path.join(os.path.dirname(__file__), 'templates/pers.html')
            data = template.render(path, template_values)
#            memcache.set(hashString, data, 10)
            return data


    def get(self):
        if not users.get_current_user():
            self.redirect('/')
            return

        self.response.out.write(self.get_page_data())

    def post(self):
        if not users.get_current_user():
            return

        pers = persons.getCurrentPerson()

        action = self.request.get('action')
        if action=='Save':
            params = ['persConsitution', 'persWeaponLaser', 'persWeaponPlasma', 'persWeaponRocket', 'persWeaponEnergy',
                      'persWeaponMiner', 'persWeaponGravity', 'persReaction', 'persEndurance', 'persObservation',
                      'persIntuition', 'persEngineer', 'persIntellect', 'persDefensiveSys', 'persJammingSys',
                      'persBiomodule', 'persWorker', 'persSciPhysic', 'persSciPower', 'persSciMath',
                      'persLevel'
            ]
            for param in params:
                self.updatePers(pers=pers, name=param)
            pers.put()

        self.response.out.write(self.get_page_data())

def main():
    application = webapp.WSGIApplication([('/pers', MainHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()
